package com.example.asa;

import com.example.asa.DatabaseUtil;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role"); // 从前端获取的角色

        // 参数非空检查
        if (username == null || username.isEmpty() || password == null || password.isEmpty() || role == null || role.isEmpty()) {
            request.setAttribute("error", "用户名、密码和角色都是必填项");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            // 获取数据库连接
            conn = DatabaseUtil.getConnection();

            // 查询用户数据（包括角色）
            String sql = "SELECT * FROM users WHERE username = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);

            rs = stmt.executeQuery();

            // 验证用户是否存在
            if (rs.next()) {
                String storedHashedPassword = rs.getString("password");
                String dbRole = rs.getString("role");

                // 添加调试输出
                System.out.println("开始处理登录请求...");
                System.out.println("用户名: " + username);
                System.out.println("提交的角色: " + role);
                System.out.println("数据库中的角色: " + dbRole);

                // 空值检查
                if (storedHashedPassword == null || dbRole == null) {
                    request.setAttribute("error", "用户信息不完整，请联系管理员");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                    return;
                }

                // 验证密码 AND 角色是否一致
                if (BCrypt.checkpw(password, storedHashedPassword) && dbRole.equals(role)) {
                    // 登录成功，创建会话
                    HttpSession session = request.getSession();
                    session.setAttribute("user", username);
                    session.setAttribute("role", dbRole); // 使用数据库中的角色信息

                    // 添加调试输出
                    System.out.println("登录成功 - 数据库读取的角色: " + dbRole);

                    // 根据角色跳转到不同页面
                    if ("resident".equals(dbRole)) {
                        System.out.println("跳转到普通居民页面");
                        request.getRequestDispatcher("clviLianPage.jsp").forward(request, response); // 简化路径测试
                    } else if ("emergency".equals(dbRole)) {
                        System.out.println("跳转到应急人员页面");
                        request.getRequestDispatcher("emergencyPage.jsp").forward(request, response); // 简化路径测试
                    } else {
                        // 不明角色处理
                        System.err.println("未知角色: " + dbRole);
                        request.setAttribute("error", "系统错误：未知角色");
                        request.getRequestDispatcher("index.jsp").forward(request, response);
                    }
                } else {
                    // 密码或角色不匹配
                    System.out.println("密码或角色不匹配");
                    request.setAttribute("error", "用户名、密码或角色不匹配");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
            } else {
                // 用户不存在
                System.out.println("用户不存在");
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            System.err.println("SQL异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("error", "登录失败：" + e.getMessage());
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } finally {
            // 关闭数据库资源
            try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
            try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
            try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
